package com.bomberdroid.protocols;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

/** This class handles a Bluetooth socket and its streams for communication */
public class ConnectedThread extends Thread {
    
    private static final int MESSAGE_READ = 158;
    
	private BluetoothSocket socket;
    private InputStream inStream;
    private OutputStream outStream;
    private Handler handler;
 
    public ConnectedThread(BluetoothSocket socket, Handler handler) {
        this.socket = socket;
        this.handler = handler;
 
        try {
            this.inStream = this.socket.getInputStream();
            this.outStream = this.socket.getOutputStream();
        } catch (IOException e) { }
    }
 
    public void run() {
    	
    	byte[] buffer = new byte[4096];  // buffer store for the stream
        int bytes; // bytes returned from read()
 
        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = this.inStream.read(buffer);
        		
                // Send the obtained bytes to the UI activity
                this.handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer.clone()).sendToTarget();
                
            } catch (IOException e) {
        		Log.d("Communication", "Failed reading");
        		this.cancel();
        		e.printStackTrace();
        		break;
            }
        }
    }
 
    /* Call this from the main activity to send data to the remote device */
    public void write(String msg) throws Exception{
        try {
    		Log.d("Communication", "Thread write : "+msg);
            this.outStream.write(msg.getBytes());
        } catch (IOException e) { }
    }
    
    public void flush(){
    	try {
			this.outStream.flush();
		} catch (IOException e) {e.printStackTrace();}
    }
 
    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
		try{
			Log.d("Communication", "Closing "+this.socket.getRemoteDevice().getName()+" link.");
		}
		catch(Exception e){
			Log.d("Communication", "Closing unknown link.");
		}
    	if(this.inStream != null){
            try {this.inStream.close();} catch (IOException e) { }
    		this.inStream = null;
    	}
    	if(this.outStream != null){
            try {this.outStream.close();} catch (IOException e) { }
    		this.outStream = null;
    	}
    	if(this.socket != null){
            try {this.socket.close();} catch (IOException e) { }
    		this.socket = null;
    	}
    	this.handler = null;
    }
    
    public BluetoothDevice getRemoteDevice(){
    	return this.socket.getRemoteDevice();
    }

	public BluetoothSocket getBluetoothSocket() {
		return socket;
	}
	
	public String getIdentity(){
		return this.socket.getRemoteDevice().getName()+"\n"+this.socket.getRemoteDevice().getAddress().replace(";", "").replace("&", "");
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}
}